from flask import Flask, session, request
from redis import Redis

from myApp.controller.build_controller import build_db
from myApp.controller.message_controller import message_db
from myApp.controller.room_controller import room_db
from myApp.controller.user_controller import user_db
from myApp.controller.case_controller import case_db
from myApp.model.db import db
from flask_cors import CORS
from urllib.parse import quote


# from myApp.utils.FuZiModel import run_fuzi, model
# from myApp.utils.ChatGlmModel import run_glm

app = Flask(__name__)
CORS(app)
app.secret_key = 'CSaSvOU6h1iMb15s+GsV5TuKYSbREcBZ/g1Gjh9nCec='
app.register_blueprint(message_db)
app.register_blueprint(user_db)
app.register_blueprint(room_db)
app.register_blueprint(case_db)
app.register_blueprint(build_db)

# 配置数据库连接URI等
# 原始密码
password = "vsoft@123&"

# URL 编码密码
encoded_password = quote(password)
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://root:{encoded_password}@127.0.0.1/chatweb"

# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://chatweb:chatweb@47.94.18.5/chatweb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 避免警告
# 初始化数据库连接
db.init_app(app)

# # redis_client = Redis(host='10.144.79.100', port=6379, db=0, decode_responses=True)
redis_client = Redis(host='127.0.0.1', port=6379, db=0, decode_responses=True, password='vsoft@123&')


@app.route('/set', methods=['POST'])
def set_key_value():
    key = request.json.get('key')
    value = request.json.get('value')
    if key is not None and value is not None:
        # 设置键值对
        redis_client.set(key, value)
        # 设置键的失效时间为60秒
        redis_client.expire(key, 600)
        return {'message': f'Key-value pair set successfully with expiration time of 60 seconds for key: {key}'}
    else:
        return {'error': 'Key and value must be provided'}, 400


@app.route('/get/<key>', methods=['GET'])
def get_value(key):
    value = redis_client.get(key)
    if value is not None:
        return {key: value}
    else:
        return {'error': 'Key not found'}, 404


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
